/**
 * Created by jianglinjie on Thu Sep 21 2017
 * @flow
 */
'use strict';

import type { RegisterParam, RegisterResult } from '../types';
import type { IRegisterStrategy } from './IRegisterStrategy';
import { ErrorCode } from '../../../constants';
import { createError } from '../../../utils/ErrorUtils';
import User from '../../../db/models/User';
import { isMongoDuplicateKeyError } from '../../../utils/ErrorUtils';
import { checkPass, checkUserName } from '../../../utils/CheckUtils';
import { RegisterType } from '../../../constants';
import { md5 } from '../../../utils/StringUtils';

export default class UserNamePwdStrategy implements IRegisterStrategy {
  async register(param: RegisterParam): Promise<RegisterResult> {
    if (!checkUserName(param.userName)) {
      throw createError(400, '用户名非法', ErrorCode.USER_NAME_INVALID);
    }

    if (!checkPass(param.pwd)) {
      throw createError(400, '密码非法', ErrorCode.PASSWORD_INVALID);    
    }

    try {
      let newUser = await User.create({
        registerType: RegisterType.USERNAME_PWD,        
        userName: param.userName,
        pwd: param.pwd,
        encryptPwd: md5(param.pwd),
      });

      return newUser.toUserInfo();
    } catch (err) {
      if (isMongoDuplicateKeyError(err)) {
        //重复键错误
        throw createError(409, '用户已注册', ErrorCode.USER_HAS_REGISTER);        
      } else  {
        throw err;                
      }
    }
  }  
}